<template>


  <!-- 购物车头部组件 -->
  <div id="CartTop">
    <catrtop />
  </div>
  <!-- 购物车主题 -->
  <!-- 向后端发送请求获取数据，展示数据 -->
  <div style="display: flex; flex-direction: column; align-items: center;" id="Catalog">
    <table style="width: 80%; background-color: #e9e9e9; border-collapse: collapse;" class="table-container">
      <thead>
        <tr>
          <th class="p-2">商品编号</th>
          <th class="p-2">产品编号</th>
          <th class="p-2">属性</th>
          <th class="p-2">数量</th>
          <th class="p-2">单价</th>
          <th class="p-2">小计</th>
          <th class="p-2">取消订单</th>
        </tr>
      </thead>
      <tbody>
        <tr id="add" v-if="cartItems.length === 0">
          <td colspan="7"><b>你的购物车为空。</b></td>
        </tr>
        <tr v-if="loading">
          <td colspan="7">加载中...</td>
        </tr>
        <tr v-for="item in cartItems" :key="item.id" class="border-t">
          <td class="p-2">{{ item.id }}</td>
          <td class="p-2">{{ item.productId }}</td>
          <td class="p-2">{{ item.attribute }}</td>
          
          
          <td >
            <button  @click="decreaseQuantity(item)" :disabled="item.quantity <= 1">-</button>
            <input
              v-model="item.quantity"
              @input="updateQuantity(item)"
              min="1"
              autosize
              style="width: 50px;"
              

            />
            <button  @click="increaseQuantity(item)">+</button>
          </td>
          
           
          <td class="p-2">¥{{ item.price.toFixed(2) }}</td>
          <td class="p-2">¥{{ item.total.toFixed(2) }}</td>
          <td>
           <el-button type="success" plain @click="remove(item)">Remove</el-button>
          </td>
        </tr>
        <tr>
          <th colspan="7">
            <div class="total">
              <span>总价：</span>
              <span>¥{{ totalPrice }}</span>
            </div>
          </th>
        </tr>
      </tbody>
    </table>
    <div id="Separator">&nbsp;</div>
    <div class="pay"><el-button type="primary" @click="pay">支付</el-button></div>
  </div>



  <!--购物车底部组件-->
  <div id="CartBottom">
    <cartbottom />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted,watch ,nextTick} from 'vue';
import { useRouter } from 'vue-router';
import catrtop from '../components/CartPageTop.vue';
import cartbottom from '../components/CartPageBottom.vue';
import axios from 'axios'; // 假设你已经安装了axios;
import { ElMessage } from 'element-plus';
import { RefSymbol } from '@vue/reactivity';


// 动态获取购物车数据
// 定义购物车项的类型
interface CartItem {
  username: string,
  id: number;
  productId: number;
  attribute: string;
  price: number;
  inStock: boolean;
  quantity: number;
  total: number;
  
  
}
const cartItems = ref<CartItem[]>([]);
const loading = ref(true);
const totalPrice = ref(0);
//const id=ref(0);

  


//在组件挂载后执行一次，常用于初始化加载数据
onMounted(async () => {
  
  await fetchCartItems();
});

// 模拟登录账户数据
const loginAccount = ref({
  listOption: true
});

const router = useRouter();
//点击支付按钮
const pay = () => {
  router.push('/order')
}
//put方法更新购物车数量
const updateQuantity = async (item: CartItem) => {
  try {
    const response = await axios.put(`/api/carts/${item.id}?quantity=${item.quantity}`, null, {
      headers: {
        'Authorization': localStorage.getItem('token')
      }
    });
    const { data } = response;
    if (data.status === 0) {
      // 更新当前商品项的小计
      item.total = data.data.lineItemPrice;
      totalPrice.value = data.data.totalPrice;
      // 这里可以根据需求更新购物车总价显示
      console.log('当前商品项总价:', data.data.lineItemPrice);
      console.log('购物车总价:', data.data.totalPrice);
    } else {
      console.error('更新失败:', data.message);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};


const increaseQuantity = async (item: CartItem) => {
  item.quantity++;
  await updateQuantity(item);
};

const decreaseQuantity = async (item: CartItem) => {
  if (item.quantity > 1) {
    item.quantity--;
    await updateQuantity(item);
  }
};

//点击remove按钮
const remove = async (item: CartItem) => {
  try {
    const response = await axios.delete(`/api/carts/${item.id}`, {
      headers: {
        'Authorization': localStorage.getItem('token')
      }
    });
    totalPrice.value = response.data.data.totalPrice;
    
    
    if (response.data.status === 1) {
      ElMessage.error(response.data.message || '删除失败');
    } else {
      // 直接过滤掉被删除的项，而不是重新获取整个购物车
      cartItems.value = cartItems.value.filter(cartItem => cartItem.id !== item.id);
      // 更新总价
      updateTotalPrice();
    
      ElMessage.success('删除成功');
    }
  } catch (error) {
    console.error('删除购物车项失败:', error);
    ElMessage.error('删除失败，请重试');
  }
};

// 提取获取购物车数据的逻辑为单独的函数
const fetchCartItems = async () => {
  try {
    loading.value = true;
    const response = await axios.get('/api/carts', {
      headers: {
        'Authorization': localStorage.getItem('token')
      }
    });
    console.log('获取购物车数据：', response.data);
    const data = response.data.data;
    totalPrice.value = data.totalPrice;
    

    cartItems.value = data.carts.map((cart: any) => ({
      id: cart.item.itemId,
      productId: cart.item.productId,
      attribute: cart.item.attribute1,
      price: cart.item.listPrice,
      inStock: cart.cartList.inStock,
      quantity: cart.cartList.quantity,
      total: cart.itemPrice,
      
    }));
  } catch (err) {
    console.error('获取购物车失败:', err);
  } finally {
    loading.value = false;
  }
};

const updateTotalPrice = () => {
  totalPrice.value = cartItems.value.reduce((sum, item) => sum + item.total, 0);
};
</script>

<style scoped>
#Catalog {
  margin-bottom: 15vh;
}

/* 可以在这里添加购物车页面的样式 */
.table-container {
  width: 60%;
  background-color: #e9e9e9;
  border-collapse: collapse;
  border: 3px solid white;
}

.table-container th {
  font-size: 25px;
  font-weight: 900;
  text-align: left;
  border: 2px solid white;
}

.table-container td {
  border: 2px solid white;
  padding: 8px;
  text-align: left;
  font-size: 25px;
}


</style>
